
const { createProxyServer } = require('http-proxy');
module.exports = function server(config) {
  const { proxy, port } = config;
  const Proxy = createProxyServer({});
  Proxy.on('error', function (err, req, res) {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Something went wrong. And we are reporting a custom error message.');
  });
  var server = require('http').createServer(
    function (req, res) {
      let url = req.url.replace(/^\/([\w\d_-]+)(\/?).*/, "$1");
      let path = req.url.replace(/^(\/[\w\d_-]+(\/?))/, "/");
      console.log(req.url, url, path);
      let target = proxy[url];
      if (url == 'favicon') {
        res.writeHead(200);
        res.end();
        return;
      }
      if (!url || !target) {
        res.writeHead(404, { 'Content-Type': 'text/plain;charset=utf-8' });
        res.end('未找到对应请求！');
        return;
      }
      Proxy.web(req, res, { target: target + path, ignorePath: true, changeOrigin: false });
    });

  server.on('close', () => {
    console.log('end success');
  })
  server.listen(port, () => {
    console.log('start success');
  });
  return server
}